package com.lhn.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @author lhn
 * @date 2024-08-22 13:07
 */
@Component
@Aspect
public class MyAdvice {

    @Pointcut("execution(* com.lhn.dao.BookDao.findNameById(..))")
    private void pc_dao() {}

    //通过 JoinPoint 或者其他特定对象来获取方法的信息和参数
//    @Before("pc_dao()")
    public void before(JoinPoint jp) {
        System.out.println("before advice ...");
        Object[] args = jp.getArgs();
        System.out.println("before advice jp args is " + Arrays.toString(args));
    }

//    @After("pc_dao()")
    public void after(JoinPoint jp) {
        System.out.println("after advice ...");
        Object[] args = jp.getArgs();
        System.out.println("after advice jp args is " + Arrays.toString(args));
    }

//    @Around("pc_dao()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        args[0] = 666;  //在这可以对传入的参数进行校验等
        System.out.println("around before advice ...");
        Object ret = pjp.proceed(args); //pjp.proceed()无参默认传入args
        System.out.println("around after advice ...");
        return ret;
    }

//    @AfterReturning(value = "pc_dao()", returning = "ret")  //returning用于获取返回值
    public void afterReturning(JoinPoint jp, Object ret) {
        System.out.println("afterReturning advice ..." + ret);
        Object[] args = jp.getArgs();
        System.out.println("after Returning jp args is " + Arrays.toString(args));
    }

    @AfterThrowing(value = "pc_dao()", throwing = "ex") //throwing用于获取异常
    public void afterThrowing(Throwable ex) {
        System.out.println("afterThrowing advice ...");
    }
}
